package com.lagou.task04;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {

    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;

        try {
            // 1.创建 ServerSocket 类型的对象，提供端口号。
            ss = new ServerSocket(8888);

            // 2.等待客户端的链接请求 accept
            System.out.println("服务端等待连接");
            s = ss.accept();
            System.out.println("服务端和客户端连接成功");

            // 3.输入输出流通讯
            ois = new ObjectInputStream(s.getInputStream());
            oos = new ObjectOutputStream(s.getOutputStream());

            while (true) {
                // 接收客户端发来的消息
                UserMessage userMessage = (UserMessage)ois.readObject();
                if (userMessage == null){
                    System.out.println("断开连接");
                    break;
                }
                System.out.println("服务端收到对象消息：" + userMessage);
                if (userMessage.getUser().getUserName().equals("admin") && userMessage.getUser().getPassword().equals("123456")) {
                    //符合条件，修改对象类型信息并返回
                    userMessage.setType("success");
                } else {
                    userMessage.setType("fail");
                }
                System.out.println("服务端回发对象消息：" + userMessage);
                oos.writeObject(userMessage);
                System.out.println();
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 4.关闭
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
